import {
  request
} from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime'
import PubSub from 'pubsub-js'

// pages/songList/index.js
Page({

  data: {
    playlist:{},
     // 请求的歌曲id
    queryIds: "",
    songList:[],
    index:0
  },

  onLoad: function (options) {
    let currentId = options.id
    this.getSongList(currentId)

    
    //订阅来自详情页的发布消息
    PubSub.subscribe('switchType',(msg,type)=>{
      let {songList , index} = this.data
      if(type === 'pre'){ //上一首
        (index === 0) && (index = songList.length)
        index -= 1
      }
      else if(type === 'loop'){ // 循环播放
        index = index
      }
      
      else{ //  下一首
        (index === songList.length-1) && (index = -1)
        index += 1
      }

      this.setData({
        index
      })
      let musicId = songList[index].id

      //发布消息
      PubSub.publish("musicId",musicId)

    })
  },

  //获取歌单详情
  async getSongList(id){
    let {data} = await request({url:"/playlist/detail",data:{id:id}})

    let {queryIds} = this.data

    data.playlist.trackIds.forEach((item) => {
      queryIds += item.id + ",";
    });

    let res = await request({url:"/song/detail",data:{ids:queryIds.substr(0, queryIds.length - 1)}})


    this.setData({
      playlist:data.playlist,
      queryIds,
      songList:res.data.songs
    })
  },

  toDetail(e){
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index

    this.setData({
      index
    })
    wx.navigateTo({
      url: '/pages/songDetail/index?id=' + id
    });
  },

})